package com.school.dao.impl;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.school.dao.TeacherDao;
import com.school.domain.Teacher;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

public class TeacherDaoImpl implements TeacherDao {
    private DataSource dataSource = new ComboPooledDataSource();
    private QueryRunner queryRunner = new QueryRunner(dataSource);


    @Override
    public boolean add(Teacher teacher) {
        int result;
        try {
            result = queryRunner.update("insert into teacher values(?, ?, ?, ?, ?)", null, teacher.getName(), teacher.getPwd(), teacher.getAge(), teacher.getSex());

        } catch (SQLException throwables) {
            return false;
        }
        return result == 1;
    }

    @Override
    public boolean del(long tid) {
        int result;
        try {
            result = queryRunner.update("delete from teacher where tid = ?", tid);
        } catch (SQLException throwables) {
            return false;
        }
        return result == 1;
    }

    @Override
    public boolean update(Teacher teacher) {
        int result;
        try {
            result = queryRunner.update("update teacher set name = ?, pwd = ?, age = ?, sex = ? where tid = ?", teacher.getName(), teacher.getPwd(), teacher.getAge(), teacher.getSex(), teacher.getTid());
        } catch (SQLException throwables) {
            return false;
        }
        return result == 1;
    }



    @Override
    public Teacher findById(long tid) {
        List<Teacher> execute;
        try {
            execute = queryRunner.query("select * from teacher where tid = " + tid, new BeanListHandler<>(Teacher.class));
        } catch (SQLException throwables) {
            return null;
        }
        if (execute.size() < 1) return null;
        return execute.get(0);
    }

    @Override
    public List<Teacher> findByName(String name) {
        List<Teacher> execute;
        try {
            execute = queryRunner.query("select * from teacher where name = " + name, new BeanListHandler<>(Teacher.class));
        } catch (SQLException throwables) {
            return null;
        }
        return execute;
    }

    @Override
    public List<Teacher> findAll() {
        List<Teacher> execute;
        try {
            execute = queryRunner.query("select * from teacher", new BeanListHandler<>(Teacher.class));
        } catch (SQLException throwables) {
            return null;
        }
        return execute;
    }

}
